/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.app.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.modules.app.entity.AppUser;
import org.springblade.modules.app.mapper.AppUserMapper;
import org.springblade.modules.app.service.IAppUserService;
import org.springblade.modules.app.vo.AppUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.function.Function;

/**
 * 客户端用户表 服务实现类
 *
 * @author Blade
 * @since 2019-04-03
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements IAppUserService {
	@Autowired
	CacheManager cacheManager;

	@Override
	public IPage<AppUserVO> selectAppUserPage(IPage<AppUserVO> page, AppUserVO appUser) {
		return page.setRecords(baseMapper.selectAppUserPage(page, appUser));
	}

	public AppUser readCookie(String uuid, HttpServletResponse response, javax.servlet.http.HttpServletRequest request) {
		Cookie cookie = new Cookie("WEBUSER", uuid);
		response.addCookie(cookie);
		return cacheManager.getCache("WEBCOOKIE").get(uuid, () -> (AppUser) request.getSession().getAttribute("user"));
	}

	@CacheEvict(cacheNames = "COOKIES", key = "#uuid")
	public void removeCookies(String uuid, HttpServletRequest request, HttpServletResponse response) {
		this.opearCookie(request, response, c -> {
			c.setMaxAge(0);
			response.addCookie(c);
			return null;
		});
	}

	public AppUser getUserByCookie(HttpServletRequest request, HttpServletResponse response) {
		return this.opearCookie(request, response, c -> this.readCookie(c.getValue(), response, request));
	}

	private AppUser opearCookie(HttpServletRequest request, HttpServletResponse response, Function<Cookie, AppUser> f) {
		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return null;
		}
		for (Cookie c : cookies) {
			if (c.getName().equals("WEBUSER")) {
				return f.apply(c);
			}
		}
		return null;
	}


}
